<template>
  <div class="payment-confirm">
    <n-card title="确认支付" class="confirm-card">
      <n-descriptions bordered>
        <n-descriptions-item label="订单号">
          {{ orderInfo.orderNo }}
        </n-descriptions-item>
        <n-descriptions-item label="服务类型">
          {{ orderInfo.serviceType }}
        </n-descriptions-item>
        <n-descriptions-item label="支付金额" :span="2">
          <span class="amount">¥ {{ orderInfo.amount }}</span>
        </n-descriptions-item>
      </n-descriptions>

      <div class="qrcode-section" v-if="qrCode">
        <div class="qrcode-wrapper">
          <img :src="qrCode" alt="支付二维码" />
          <p class="qrcode-tip">请使用支付宝扫码支付</p>
        </div>
        <n-space vertical>
          <n-button type="primary" @click="refreshQrCode">
            刷新二维码
          </n-button>
          <n-button @click="cancelPayment">
            取消支付
          </n-button>
        </n-space>
      </div>

      <div class="payment-status" v-if="orderInfo.status === 'PENDING'">
        <n-spin size="large" />
        <p>正在等待支付...</p>
      </div>

      <div class="payment-success" v-if="orderInfo.status === 'PAID'">
        <n-result
          status="success"
          title="支付成功"
          description="感谢您的支付，我们将尽快为您处理"
        >
          <template #footer>
            <n-space>
              <n-button @click="goToOrders">
                查看订单
              </n-button>
              <n-button type="primary" @click="goToHome">
                返回首页
              </n-button>
            </n-space>
          </template>
        </n-result>
      </div>
    </n-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { getOrderDetail, getPaymentQrCode, queryPaymentStatus, cancelOrder } from '@/api/payment'

const route = useRoute()
const router = useRouter()
const message = useMessage()

const orderNo = ref(route.params.orderNo)
const orderInfo = ref({})
const qrCode = ref('')
const statusTimer = ref(null)

// 获取订单详情
const getOrder = async () => {
  try {
    const res = await getOrderDetail(orderNo.value)
    if (res.code === 0) {
      orderInfo.value = res.data
      if (orderInfo.value.status === 'PENDING') {
        await getQrCode()
        startStatusCheck()
      }
    }
  } catch (error) {
    message.error('获取订单信息失败')
  }
}

// 获取支付二维码
const getQrCode = async () => {
  try {
    const res = await getPaymentQrCode(orderNo.value)
    if (res.code === 0) {
      qrCode.value = res.data
    }
  } catch (error) {
    message.error('获取支付二维码失败')
  }
}

// 刷新二维码
const refreshQrCode = () => {
  getQrCode()
}

// 开始检查支付状态
const startStatusCheck = () => {
  stopStatusCheck()
  statusTimer.value = setInterval(checkPaymentStatus, 3000)
}

// 停止检查支付状态
const stopStatusCheck = () => {
  if (statusTimer.value) {
    clearInterval(statusTimer.value)
    statusTimer.value = null
  }
}

// 检查支付状态
const checkPaymentStatus = async () => {
  try {
    const res = await queryPaymentStatus(orderNo.value)
    if (res.code === 0) {
      if (res.data.status === 'PAID') {
        orderInfo.value = res.data
        stopStatusCheck()
        message.success('支付成功')
      }
    }
  } catch (error) {
    console.error('查询支付状态失败:', error)
  }
}

// 取消支付
const cancelPayment = async () => {
  try {
    const res = await cancelOrder(orderNo.value)
    if (res.code === 0) {
      message.success('订单已取消')
      stopStatusCheck()
      router.push('/orders')
    }
  } catch (error) {
    message.error('取消订单失败')
  }
}

// 跳转到订单列表
const goToOrders = () => {
  router.push('/orders')
}

// 跳转到首页
const goToHome = () => {
  router.push('/')
}

onMounted(() => {
  getOrder()
})

onBeforeUnmount(() => {
  stopStatusCheck()
})
</script>

<style scoped>
.payment-confirm {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.confirm-card {
  margin-bottom: 20px;
}

.amount {
  font-size: 24px;
  color: #f5222d;
  font-weight: bold;
}

.qrcode-section {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 40px;
}

.qrcode-wrapper {
  text-align: center;
}

.qrcode-wrapper img {
  width: 200px;
  height: 200px;
  margin-bottom: 10px;
}

.qrcode-tip {
  color: #666;
  margin: 10px 0;
}

.payment-status {
  margin-top: 30px;
  text-align: center;
}

.payment-status p {
  margin-top: 10px;
  color: #666;
}

.payment-success {
  margin-top: 30px;
}
</style>
